﻿using IGL_Talk_Win8.Model;
using System;
using System.Linq;
using Windows.ApplicationModel.Resources.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace IGL_Talk_Win8.Controls
{
    public sealed partial class LanguageSelection : UserControl
    {
        public LanguageSelection()
        {
            this.InitializeComponent();

            var currentUiCulture = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            var langOverride = Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride;
            comboLanguageSelection.SelectedValue = string.IsNullOrEmpty(langOverride) ? currentUiCulture : langOverride;
        }

        private void comboLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count == 0)
            {
                return;
            }

            var selected = e.AddedItems.FirstOrDefault();

            if (selected != null)
            {
                var lang = selected as Language;
                Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = lang.Code;
                System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo(lang.CultureInfo);

                AppCloseDialog();
            }
        }

        private async void AppCloseDialog()
        {
            var loader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();
            string messageTitle = loader.GetString("LanguageSelection_PopupTitle");
            string messageText = loader.GetString("LanguageSelection_PopupText");
            string yes = loader.GetString("Dialog_Yes");
            string no = loader.GetString("Dialog_No");

            var messageDialog = new MessageDialog(messageText,messageTitle);

            messageDialog.Commands.Add(new UICommand(
                yes,
                new UICommandInvokedHandler(this.CommandInvokedHandler),
                0));
            messageDialog.Commands.Add(new UICommand(
                no,
                new UICommandInvokedHandler(this.CommandInvokedHandler),
                1));

            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;

            await messageDialog.ShowAsync();
        }

        private void CommandInvokedHandler(IUICommand command)
        {
            if(command.Id.Equals(0))
            {
                Application.Current.Exit();
            }
        }
    }
}